---
- name: ubuntu22.04存储机环境部署
  remote_user: ht
  become: yes
  become_method: sudo
  hosts: all
  tasks:
    - name: 安装smartmontools
      apt:
        name: smartmontools=7.2-1ubuntu0.1
        update_cache: true
      ignore_errors: yes

    - name: 创建必备的文件夹
      file:
        path: "{{ item }}"
        state: directory
      with_items:
      - /usr/local/node_exporter
      - /usr/local/node_exporter/metrics
      - /usr/local/node_exporter/scripts

    - name: 复制监控服务和监控软件到主机
      copy:
        src: '{{ item.src }}'
        dest: '{{ item.dest }}'
        mode: a+x
      with_items:
      - { src: "/root/PlayBook/inventory/node_exporter/node_exporter.service",dest: "/etc/systemd/system/"}
      - { src: "/root/PlayBook/inventory/node_exporter/node_exporter",dest: "/usr/local/node_exporter/"}
      - { src: "/root/PlayBook/inventory/node_exporter/scripts/smartmon.sh",dest: "/usr/local/node_exporter/scripts/"}

    - name: 打开node_exporter服务并设置开机启动
      service:
        name: '{{ item.name }}'
        state: started
        enabled: yes
      with_items:
      - { name: "node_exporter"}

    - name: 创建smartmon.sh的cron定时运行
      cron:
        name: 运行/usr/local/node_exporter/scripts/smartmon.sh
        minute: '*/5'
        job: '/usr/local/node_exporter/scripts/smartmon.sh > /usr/local/node_exporter/metrics/smart_metrics.prom'


    - name: 复制修改主机名脚本
      copy:
        src: /root/PlayBook/inventory/1store-hostname.sh
        dest: /root/
        mode: 0755

    - name: 修改主机名
      shell: bash /root/1store-hostname.sh
      register: result
      failed_when: false

    - name: 设置上海时区
      shell:
       cmd: timedatectl set-timezone Asia/Shanghai

    - name: 确保允许 root 用户密码登录
      become: yes
      become_method: sudo
      lineinfile:
        path: /etc/ssh/sshd_config
        regexp: '^PermitRootLogin'
        line: 'PermitRootLogin yes'
        state: present
        create: yes  # 如果文件不存在，将创建它

    - name: 重启 SSH 服务
      become: yes
      become_method: sudo
      service:
        name: sshd
        state: restarted


    - name: 修改/设置密码
      user:
       name: '{{ item.user }}'
       password: "{{ item.password | password_hash('sha512') }}"
       update_password: always
      with_items:
       - { user: 'root', password: 'hty-admin'}
       - { user: 'yunwei', password: 'hty-yunwei'}
       - { user: 'ht', password: 'hty-yanfa1'}
